//
//  JKEmojiKeyboardTextView.swift
//  表情键盘
//
//  Created by albert on 16/6/27.
//  Copyright © 2016年 albert. All rights reserved.
//  自定义textView

import UIKit

class JKEmojiKeyboardTextView: UITextView {

    /** 插入表情 */
    func insertEmoticon(emoticon: JKEmojiModel) {
        // 1.emoji表情的图文混排
        if let emojiStr = emoticon.emoticonStr {
            // 1.1取出光标所在位置
            let range = selectedTextRange!
            
            // 1.2用emoji表情替换光标所在位置
            replaceRange(range, withText: emojiStr)
            
            return
        }
        
        // 2.新浪表情的图文混排
        if let tempPngPath = emoticon.pngPath {
            // 2.1通过textView中的属性字符串文字创建属性字符串
            let attrMStr = NSMutableAttributedString(attributedString: attributedText)
            
            // 2.2创建图片的属性字符串
            let attachment = JKEmojiKeyboardAttachment()
            attachment.emoticonChs = emoticon.chs
            let fontHeight = font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
            attachment.image = UIImage(contentsOfFile: tempPngPath)
            let imageAttrStr = NSAttributedString(attachment: attachment)
            
            // 2.3获取光标所在的位置
            let range = selectedRange
            
            // 2.4将光标所在位置的字符串进行替换
            attrMStr.replaceCharactersInRange(range, withAttributedString: imageAttrStr)
            
            // 2.5显示可变属性字符串即可
            attributedText = attrMStr
            
            // 2.6确定光标的位置，光标放在插入图片的后面
            selectedRange = NSRange(location: range.location + 1, length: 0)
            
            // 2.7重新设置大小
            font = UIFont.systemFontOfSize(18)
        }
        
        // 3.删除最近一个字母或者表情
        if emoticon.isDeleteButton {
            deleteBackward()
        }
    }

    /** 获取textView的文字和表情 */
    func getTextAndEmoticon() -> String {
        
        guard hasText() else {
            return "分享图片"
        }
        
        // 1.获取textView整个字符串的range
        let range = NSRange(location: 0, length: attributedText.length)
        
        // 2.创建可变字符串（之后将取出的字符串和表情拼接到可变字符串）
        var strM = String()
        
        // 3.遍历属性字符串
        attributedText.enumerateAttributesInRange(range, options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            
            if let tempAttachment = dict["NSAttachment"] as? JKEmojiKeyboardAttachment {
                // 拼接表情对应的字符串
                strM += tempAttachment.emoticonChs!
                
            }else {
                // 拼接文字，也可以使用self.textView.attributedText.string
                strM += (self.text as NSString).substringWithRange(range)
            }
        }
        
        return strM
    }
}
